package com.hooper.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hooper.common.util.helper.HttpRequestHelper;
import com.hooper.hosp.client.HospClient;
import com.hooper.hosp.enums.OrderStatusEnum;
import com.hooper.hosp.model.order.OrderInfo;
import com.hooper.hosp.model.user.Patient;
import com.hooper.hosp.vo.hosp.ScheduleOrderVo;
import com.hooper.hosp.vo.msm.MsmVo;
import com.hooper.hosp.vo.order.OrderMqVo;
import com.hooper.hosp.vo.order.OrderQueryVo;
import com.hooper.hosp.vo.order.SignInfoVo;
import com.hooper.hospital.common.exception.HospitalException;
import com.hooper.hospital.common.result.ResultCodeEnum;
import com.hooper.hospital.common.utils.ObjectUtils;
import com.hooper.order.mapper.OrderMapper;
import com.hooper.order.service.OrderService;
import com.hooper.order.service.WeixinService;
import com.hooper.rabbit.constant.MqConstant;
import com.hooper.rabbit.service.RabbitService;
import com.hooper.user.client.UserClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2022/10/09/19:55
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    @Resource
    private UserClient userClient;
    @Resource
    private HospClient hospClient;
    @Resource
    private RabbitService rabbitService;
    @Resource
    private WeixinService weixinService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveOrder(String scheduleId, Long patientId) {
        ScheduleOrderVo scheduleOrderVo = hospClient.getScheduleOrderVo(scheduleId);
        log.warn(scheduleOrderVo.toString());
        //判断当前时间是否还可以预约
        if (scheduleOrderVo.getStartTime().after(new Date()) || scheduleOrderVo.getEndTime().before(new Date())) {
            throw new HospitalException(ResultCodeEnum.TIME_NO);
        }
        Patient patient = userClient.getPatient(patientId);
        SignInfoVo signInfoVo = hospClient.getSignInfoVo(scheduleOrderVo.getHoscode());
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setScheduleId(scheduleId);
        //生成订单号
        orderInfo.setOutTradeNo(scheduleOrderVo.getHoscode() + System.currentTimeMillis() + new Random(1000).nextInt() + "");
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        //将订单信息保存到数据库中
        this.save(orderInfo);

        Map<String, Object> paramMap = new HashMap<>(20);
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", scheduleOrderVo.getHosScheduleId());
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());
        //联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);
        log.warn(signInfoVo.toString());
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");
        if (result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");

            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");

            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");

            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            //发送mq信息更新号源和短信通知
            //发送mq信息更新号源
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            msmVo.setTemplateCode("SMS_194640721");
            String reserveDate =
                    new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                            + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>(5) {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);

            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConstant.EXCHANGE_DIRECT_ORDER, MqConstant.ROUTING_ORDER, orderMqVo);

        } else {
            throw new HospitalException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();
    }

    @Override
    public OrderInfo getOrderById(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            throw new HospitalException(ResultCodeEnum.PARAM_EMPTY);
        }
        return packageOrderInfo(this.getById(orderId));
    }

    @Override
    public IPage<OrderInfo> pageByConditions(Integer currentPage, Integer pageSize, OrderQueryVo queryVo, Long userId) {
        if (ObjectUtils.isAnyNull(currentPage, pageSize)) {
            throw new HospitalException(ResultCodeEnum.PARAM_EMPTY);
        }
        IPage<OrderInfo> page = new Page<>(currentPage, pageSize);
        //判断用户是否登录
        if (userId == null) {
            throw new HospitalException(ResultCodeEnum.LOGIN_REQUIRE);
        }
        //如果搜索框为空直接返回所有
        if (queryVo == null) {
            baseMapper.selectPage(page, null);
            page.getRecords().forEach(this::packageOrderInfo);
            return page;
        }

        String hosname = queryVo.getKeyword();
        String orderStatus = queryVo.getOrderStatus();
        //安排时间
        String reserveDate = queryVo.getReserveDate();
        String createTimeBegin = queryVo.getCreateTimeBegin();
        String createTimeEnd = queryVo.getCreateTimeEnd();
        String patientName = queryVo.getPatientName();

        //条件查询
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getUserId, userId)
                .like(StringUtils.isNotEmpty(hosname), OrderInfo::getHosname, hosname)
                .eq(StringUtils.isNotEmpty(orderStatus), OrderInfo::getOrderStatus, orderStatus)
                .like(StringUtils.isNotEmpty(patientName), OrderInfo::getPatientName, patientName)
                .ge(StringUtils.isNotEmpty(createTimeBegin), OrderInfo::getCreateTime, createTimeBegin)
                .le(StringUtils.isNotEmpty(createTimeEnd), OrderInfo::getCreateTime, createTimeEnd)
                .ge(StringUtils.isNotEmpty(reserveDate), OrderInfo::getReserveDate, reserveDate);
        baseMapper.selectPage(page, wrapper).getRecords().forEach(this::packageOrderInfo);
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean cancelOrder(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            throw new HospitalException(ResultCodeEnum.PARAM_EMPTY);
        }
        OrderInfo orderInfo = this.getById(orderId);
        Date quitTime = orderInfo.getQuitTime();
        //判断取消订单时间是否超过原定的时间
        if (quitTime.before(new Date())) {
            throw new HospitalException(ResultCodeEnum.EXCEED_QUIT_TIM);
        }
        //调用医院接口实现预约取消
        //获取医院签名
        SignInfoVo signInfoVo = hospClient.getSignInfoVo(orderInfo.getHoscode());
        if (ObjectUtils.isNull(signInfoVo)) {
            throw new HospitalException(ResultCodeEnum.SIGN_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>(10);
        reqMap.put("hoscode", orderInfo.getHoscode());
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        JSONObject respData = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl() + "/order/updateCancelStatus");
        if (respData.getInteger("code") != 200) {
            throw new HospitalException(respData.getString("message"), respData.getInteger("code"));
        } else {
            if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()) {
                //已支付 调用微信接口退款
                boolean refunded = weixinService.refund(Long.valueOf(orderId));
                if (!refunded) {
                    throw new HospitalException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
            }
            //否则 只取消订单不用退款
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            this.updateById(orderInfo);
            //发送mq信息更新预约数 我们与下单成功更新预约数使用相同的mq信息，不设置可预约数与剩余预约数，接收端可预约数减1即可
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getScheduleId());
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            msmVo.setTemplateCode("SMS_194640722");
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>(4) {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConstant.EXCHANGE_DIRECT_ORDER, MqConstant.ROUTING_ORDER, orderMqVo);
        }
        return true;

    }

    private OrderInfo packageOrderInfo(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return null;
        }
        Map<String, Object> param = orderInfo.getParam();
        param.put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }
}
